package com.example.music.ui.adapters

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.music.R
import com.example.music.data.Music
import java.text.SimpleDateFormat
import java.util.*

class MusicAdapter(
    private val onMusicClick: (Music) -> Unit
) : RecyclerView.Adapter<MusicAdapter.MusicViewHolder>() {
    
    private var musicList = listOf<Music>()
    private var currentMusic: Music? = null
    
    fun updateMusicList(newMusicList: List<Music>) {
        musicList = newMusicList
        notifyDataSetChanged()
    }
    
    fun setCurrentMusic(music: Music?) {
        val oldPosition = musicList.indexOf(currentMusic)
        currentMusic = music
        val newPosition = musicList.indexOf(currentMusic)
        
        if (oldPosition != -1) {
            notifyItemChanged(oldPosition)
        }
        if (newPosition != -1) {
            notifyItemChanged(newPosition)
        }
    }
    
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MusicViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_music, parent, false)
        return MusicViewHolder(view)
    }
    
    override fun onBindViewHolder(holder: MusicViewHolder, position: Int) {
        val music = musicList[position]
        holder.bind(music, music == currentMusic)
    }
    
    override fun getItemCount(): Int = musicList.size
    
    inner class MusicViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val songTitle: TextView = itemView.findViewById(R.id.songTitle)
        private val songArtist: TextView = itemView.findViewById(R.id.songArtist)
        private val songAlbum: TextView = itemView.findViewById(R.id.songAlbum)
        private val songDuration: TextView = itemView.findViewById(R.id.songDuration)
        private val playStatusIcon: ImageView = itemView.findViewById(R.id.playStatusIcon)
        
        fun bind(music: Music, isPlaying: Boolean) {
            songTitle.text = music.title
            songArtist.text = music.artist ?: "未知艺术家"
            songAlbum.text = music.album ?: "未知专辑"
            songDuration.text = formatDuration(music.duration)
            
            playStatusIcon.visibility = if (isPlaying) View.VISIBLE else View.GONE
            
            itemView.setOnClickListener {
                onMusicClick(music)
            }
        }
        
        private fun formatDuration(duration: Long): String {
            val minutes = duration / 60000
            val seconds = (duration % 60000) / 1000
            return String.format("%d:%02d", minutes, seconds)
        }
    }
}
